package cn.com.dwr.service.impl;

import cn.com.dwr.entity.*;
import cn.com.dwr.service.AppCategoryService;
import cn.com.dwr.service.AppSkuStockService;
import cn.com.dwr.service.AppSpecificationValueService;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.com.dwr.service.AppProductService;
import cn.com.dwr.mapper.AppProductMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author 邓文润
* @description 针对表【app_product】的数据库操作Service实现
* @createDate 2023-12-12 07:13:55
*/
@Service
public class AppProductServiceImpl extends ServiceImpl<AppProductMapper, AppProduct>
    implements AppProductService{

    @Resource
    AppCategoryService appCategoryService;

    @Resource
    AppSpecificationValueService appSpecificationValueService;

    @Resource
    AppSkuStockService appSkuStockService;

    @Override
    public Object pageByCategoryId(Page page, Long categoryId, Integer sort) {

        AppCategory category = appCategoryService.getById(categoryId);
        Assert.notNull(category, "商品分类不存在");

        Page pageData = this.page(page, new QueryWrapper<AppProduct>()
                .eq("is_on_sale", true)
                .eq("category_id", categoryId)
                .orderByDesc(sort == 0, "is_top", "sort_order")
                .orderByDesc(sort == 1, "created")
                .orderByDesc(sort == 2, "sale")
        );

        return MapUtil.builder()
                .put("category", category)
                .put("pageData", pageData)
                .build();
    }

    @Override
    public AppProduct getWithAttrsById(Long productId) {

        // 商品详情
        AppProduct product = this.getById(productId);
        Assert.notNull(product, "商品不存在");

        // 商品属性
        List<AppSpecificationValue> list = appSpecificationValueService.listByProductId(productId);
        product.setSpecifications(list);

        // 商品可选组合（sku stock、price）  sku：商品库存最小的存货单位
        List<AppSkuStock> skuStocks = appSkuStockService.listByProductId(productId);
        product.setSkuStocks(skuStocks);

        return product;
    }
}

